package org.leopard.rpc.rmi;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.leopard.rpc.Producer;
import org.leopard.rpc.RPCContext;
import org.leopard.rpc.ServiceCenter;

/**
 * @author IBM CHEN ZHI KAN
 * @create 2018/8/13
 */
public class RMIProducer extends Producer {
  private String rmiUrl=null;

  public RMIProducer(String host, String port, String klassName) {
    super(host, port, klassName);
  }

  public String getRmiUrl() {
    if(rmiUrl==null||rmiUrl.equals("")){
      this.rmiUrl=String.format("%s://%s","rmi",this.getUrl());
    }
    return rmiUrl;
  }

  /**
   * rmi注册服务，并且在zk上注册临时有序节点
   * @param serviceCenter
   * @return
   */
  public boolean publish(ServiceCenter serviceCenter) {
    publishService();
    boolean flag=serviceCenter.createChildNode(RPCContext.RPC_CHILD_NODE_PATH,this.getRmiUrl().getBytes(),
        Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
    if(flag){
      System.out.println("服务发布成功");
    }else {
      System.out.println("服务发布失败");
    }
    return flag;
  }

  /**
   * rmi注册服务
   */
  private void publishService(){
    try {
      Class remote=Class.forName(this.getKlassName());
      LocateRegistry.createRegistry(Integer.parseInt(this.getPort()));
      Naming.rebind(this.getRmiUrl(), (Remote) remote.newInstance());
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InstantiationException e) {
      e.printStackTrace();
    }
  }
}
